package com.anhtuan.reminder.services;

import java.util.Calendar;
import java.util.Date;

import com.anhtuan.reminder.tasks.StartAlarmTask;
import com.anhtuan.reminder.tasks.StopAlarmTask;
import com.anhtuan.reminder.ultils.RepeatItem;
import com.anhtuan.reminder.ultils.Ultils;

import android.app.AlarmManager;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class ScheduleService extends Service {

	
	private final IBinder binder = new ServiceBinder();
	
	@Override
	public IBinder onBind(Intent intent) {
		return binder;
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		return START_STICKY;
	}
	
	public void startScheduleATask(int taskId, int repeat, int day, String time) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.SECOND, 0);
		
		Date currentDate = calendar.getTime();
		Date todoDate = Ultils.convertToDate(time, "hh:mm");
		
		long intervalMillis = 0;
		
		if (todoDate.getHours() >= currentDate.getHours() && todoDate.getMinutes() >= currentDate.getMinutes()) {
			
			intervalMillis = (todoDate.getHours() - currentDate.getHours()) * 3600 + (todoDate.getMinutes() - currentDate.getMinutes()) * 60;
			
		} else {
			
			intervalMillis = (86400 - (currentDate.getHours() * 3600 + currentDate.getMinutes() * 60)) // time -> 23h59
							+ ((todoDate.getHours() * 3600 + todoDate.getMinutes() * 60)); // time from 0h ->
		}
		
		intervalMillis *= 1000;
		
		switch (repeat) {
		case RepeatItem.NOT_REPEATED:
			
			calendar.setTimeInMillis(calendar.getTimeInMillis() + intervalMillis);
			
			new StartAlarmTask(taskId, this, calendar, false, 0).run();
			
			break;

		case RepeatItem.REPEAT_WEEKLY:
					
			if (day >= calendar.get(Calendar.DAY_OF_WEEK)) {
				intervalMillis  += (day - calendar.get(Calendar.DAY_OF_WEEK)) * 86400 * 1000;
			} else {
				intervalMillis += (7 - calendar.get(Calendar.DAY_OF_WEEK) + day) * 86400 * 1000;
			}
			
			calendar.setTimeInMillis(calendar.getTimeInMillis() + intervalMillis);
			
			// Start schedule
			new StartAlarmTask(taskId, this, calendar, true, AlarmManager.INTERVAL_DAY * 7).run();
			
			break;
			
		case RepeatItem.REPEAT_DAILY:
			
			calendar.setTimeInMillis(calendar.getTimeInMillis() + intervalMillis);
			
			// Start schedule
			new StartAlarmTask(taskId, this, calendar, true, AlarmManager.INTERVAL_DAY).run();
			
			break;
			
		default:
			break;
		}		
	}
	
	public void stopScheduleATask (int taskId) {
		new StopAlarmTask(taskId, this).run();
	}
	
	public class ServiceBinder extends Binder {
		ScheduleService getService() {
			return ScheduleService.this;
		}
	}
}
